package servlet;

import entity.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:石小俊
 * @Date: 2022/12/27 9:05
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        if("/findAll.user".equals(path)){
            findAll(request,response);
        }
        if("/findById.user".equals(path)){
            findById(request,response);
        }
    }

    public void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String id = request.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        User user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address")
                    .append(" from t_user ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            rs = ps.executeQuery();
            while(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));

                // 将User对象以JSON格式的字符串的方式传递到前端
                // out.print("{'id':"+user.getId()+",'username':'"+user.getUsername()+"','password':'"+user.getPassword()+"','phone':'"+user.getPhone()+"','address':'"+user.getAddress()+"'}");

                // 使用apache的JSON工具将Java对象转换成JSON格式字符串
                // 1.对象转JSON对象
                JSONObject jsonObject = JSONObject.fromObject(user);
                // JSON对象提供了转换JSON格式字符串的方式
                String userJson = jsonObject.toString();
                out.print(userJson);

                // 2.集合转JSON格式字符串
                // 将一个Java对象集合/数组转换成JSON数组
//                List<User> users = new ArrayList<>();
//                JSONArray jsonArray = JSONArray.fromObject(users);
//                // 可以将JSON数组转换成JSON数组格式的字符串
//                String usersJson = jsonArray.toString();

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        List<User> users = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                users.add(user);
            }
            request.setAttribute("users",users);
//            request.getRequestDispatcher("/list.jsp").forward(request,response);
            request.getRequestDispatcher("/jquery/list.jsp").forward(request,response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }
}
